using System;
using Godot;
using Horizoncraft.script;
using Horizoncraft.script.Entity;
using Horizoncraft.script.Net;
using Horizoncraft.script.NewProxy.player;
using Horizoncraft.script.Services.chunk;
using Horizoncraft.script.Services.entity;
using Horizoncraft.script.Services.message;
using Horizoncraft.script.Services.player;
using Horizoncraft.script.WorldControl.Tool;

namespace Horizoncraft.script.Services.world;

public class HostWorldService : WorldServiceBase
{
    public static int Port = 9999;
    public static int MaxPlayer = 10;
    
    public HostWorldService(World world) : base(world)
    {
        world.Multiplayer.PeerDisconnected += OnPlayerExit;
        var enet = new ENetMultiplayerPeer();
        enet.CreateServer(Port, MaxPlayer);
        world.Multiplayer.MultiplayerPeer = enet;
    }

    public override void InitializeServices()
    {
        EntityBehavior = new EntityBehaviorBase();
        ChunkService = AddService<HostChunkService>(new HostChunkService(World));
        PlayerService = AddService<HostPlayerService>(new HostPlayerService(World));
        EntityService = AddService<HostEntityService>(new HostEntityService(World));
        MessageService = AddService<HostMessageService>(new HostMessageService(World)); 
        
        InitializeNode();

        GD.Print($"[初始化完成]{nameof(HostWorldService)}");
    }

    private void OnPlayerExit(long id)
    {
        foreach (var player in PlayerService.Players.Values)
        {
            if (player.PeerId == id)
            {
                PlayerService.Players.TryRemove(player.Name, out var _);
                PlayerService.SavePlayer(player);
                return;
            }
        }
    }
}